package com.cloudeasy.core.handler;

import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕获{@link CloudEasyException}，返回对应的由{@link CloudEasyException}构造的失败{@link Result}
     *
     * @param e {@link CloudEasyException}
     * @return {@link Result}
     */
    @ExceptionHandler(CloudEasyException.class)
    public Result executeCloudEasyException(CloudEasyException e) {
        return ResultUtil.failure(e);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder("-");
        e.getConstraintViolations().forEach(constraintViolation -> {
            message.append(constraintViolation.getMessage()).append("-");
        });
        return ResultUtil.failure(message.toString());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder("-");
        e.getBindingResult().getAllErrors().forEach(objectError -> {
            message.append(objectError.getDefaultMessage()).append("-");
        });
        return ResultUtil.failure(message.toString());
    }

    @ExceptionHandler(BindException.class)
    public Result bindException(BindException e) {
        StringBuilder message = new StringBuilder("-");
        e.getAllErrors().forEach(objectError -> {
            message.append(objectError.getDefaultMessage()).append("-");
        });
        return ResultUtil.failure(message.toString());
    }
}
